//
//  cCChatViewController.m
//  cyChat
//
//  Created by 楼楚 on 15/12/12.
//  Copyright © 2015年 Chu Lou. All rights reserved.
//

#import "cCChatViewController.h"
#import "cCInputView.h"
#import "HttpTool.h"
#import "UIImageView+WebCache.h"


@interface cCChatViewController ()<UITableViewDataSource,UITableViewDelegate,NSFetchedResultsControllerDelegate,UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
    NSFetchedResultsController *_resultContr;
    
}
@property(nonatomic,strong) NSLayoutConstraint *inputViewConstraint;//inputview底部约束
@property(nonatomic,strong) NSLayoutConstraint *inputViewHeightConstraint;//inputview高度约束
@property(nonatomic,weak) UITableView *tableView;
@property(nonatomic,strong) HttpTool *httpTool;

@end



@implementation cCChatViewController
- (HttpTool *)httpTool
{
    if (!_httpTool) {
        _httpTool = [[HttpTool alloc]init];
    }
    return _httpTool;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setupView];
    //监听键盘
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification   object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    NSLog(@"lll");
    [self loadMsgs];
}
- (void)keyboardWillShow:(NSNotification *)noti{
//    获取键盘的高度
    CGRect kbEndFrm = [noti.userInfo[UIKeyboardFrameEndUserInfoKey]CGRectValue];
    CGFloat kbHeight = kbEndFrm.size.height;
    
    if ([[UIDevice currentDevice].systemVersion doubleValue] < 8.0 && UIInterfaceOrientationIsLandscape(self.interfaceOrientation)) {
        kbHeight = kbEndFrm.size.width;
    }
    
    self.inputViewConstraint.constant = kbHeight;
    [self scrollToTableBottom];
    NSLog(@"出现");
}
- (void)keyboardWillHide:(NSNotification *)noti
{
    NSLog(@"消失");
    
    self.inputViewConstraint.constant = 0;
}

//- (void) kbFrmWillChange:(NSNotification *)noti
//{
//    NSLog(@"%@",noti.userInfo);
//    
////获取窗口的高度
//    CGFloat windowH = [UIScreen mainScreen].bounds.size.height;
////    键盘结束的frm
//    CGRect kbEndFrm = [noti.userInfo[UIKeyboardFrameEndUserInfoKey]CGRectValue];
//    
////    获取键盘结束的y值
//    CGFloat kbEndY = kbEndFrm.origin.y;
//    
//    self.inputViewConstraint.constant = windowH - kbEndY;
//    
//    
//}

- (void) setupView
{
//    代码方式实现自动布局 VFL
//    创建一个Tableview
    UITableView *tableView = [[UITableView alloc]init];
    

    tableView.delegate = self;
    tableView.dataSource = self;
#warning 代码实现自动布局，要设置下面的属性为NO
    tableView.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self.view addSubview:tableView];
//    创建输入框View
    cCInputView *inputView = [cCInputView inputView];
   
    inputView.translatesAutoresizingMaskIntoConstraints = NO;
//    设置inputview的代理
    inputView.textView.delegate = self;
    
//添加按钮事件
    [inputView.addBtn addTarget:self action:@selector(addBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:inputView];
    self.tableView = tableView;
    
//    自动布局
    
//    水平方向的约束
  //    tableview
    NSDictionary *views = @{@"tableView":tableView,
                            @"inputView":inputView};
    
  NSArray *tableViewHConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[tableView]-0-|" options:0 metrics:nil views:views];
    [self.view addConstraints:tableViewHConstraints];
  //    inputview
    NSArray *inputViewHConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[inputView]-0-|" options:0 metrics:nil views:views];
    [self.view addConstraints:inputViewHConstraints];
//    垂直方向的约束
    NSArray *vConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-64-[tableView]-0-[inputView(50)]-|" options:0 metrics:nil views:views];
    [self.view addConstraints:vConstraints];
//    添加inputview的高度约束
    self.inputViewHeightConstraint = vConstraints[2];
    self.inputViewConstraint = [vConstraints lastObject];
    NSLog(@"%@",vConstraints);
}

#pragma mark - 加载XMPPMessageArchiving数据库的数据显示在表格
- (void)loadMsgs
{
//上下文
    NSManagedObjectContext *context = [cCXMPPTool sharedcCXMPPTool].msgStorge.mainThreadManagedObjectContext;
//    请求对象
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"XMPPMessageArchiving_Message_CoreDataObject"];
    
//    过滤、排序
//    1.当前登录用户的jid的消息
//    2。好友的jid消息

    NSPredicate *pre = [NSPredicate predicateWithFormat:@"streamBareJidStr = %@ AND bareJidStr = %@",[cCUserInfo sharedcCUserInfo].jid,self.friendJid.bare];
    request.predicate = pre;
    
//时间升序
    NSSortDescriptor *timeSort = [NSSortDescriptor sortDescriptorWithKey:@"timestamp" ascending:YES];
    request.sortDescriptors = @[timeSort];
    
//    查询
    _resultContr = [[NSFetchedResultsController alloc]initWithFetchRequest:request managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];
    NSError *err = nil;
    [_resultContr performFetch:&err];
    _resultContr.delegate = self;
    if (err) {
        NSLog(@"%@",err);
    }
}

#pragma mark - 表格的数据源
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _resultContr.fetchedObjects.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID =@"ChatCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
//    获取聊天消息对象
    XMPPMessageArchiving_Message_CoreDataObject *msg = _resultContr.fetchedObjects[indexPath.row];
    
//    判断是图片还是纯文本
    NSString *chatType = [msg.message attributeStringValueForName:@"chatType"];
    if ([chatType isEqualToString:@"image"]) {
//        下图片显示
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:msg.body] placeholderImage:[UIImage imageNamed:@"DefaultProfileHead_qq"]];
        cell.textLabel.text = nil;
    }
    else
//       else if ([chatType isEqualToString:@"text"])
        {
        
        //    显示
        if ([msg.outgoing boolValue]) {//自己发
            cell.textLabel.text = msg.body;
            
//            cell.textLabel.text = [NSString stringWithFormat:@"me: %@",msg.body];
        }else
        {
            //        别人发
            cell.textLabel.text = msg.body;

//            cell.textLabel.text = [NSString stringWithFormat:@"other: %@",msg.body];
        }
        cell.imageView.image = nil;
        
    }
    
    
    
    return cell;
    
    
}
#pragma mark -ResultsController代理
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    [self.tableView reloadData];
    [self scrollToTableBottom];
}
#pragma mark - textview代理
- (void)textViewDidChange:(UITextView *)textView
{
//    获取contentsize
    CGFloat contentH = textView.contentSize.height;
    NSLog(@"%f",contentH);
//    NSLog(@"%@",textView.text);
    
//    大于33：超过一行的高度 小于68：三行内
    if (contentH > 33 && contentH < 68) {
        self.inputViewHeightConstraint.constant = contentH + 18;
    }
    NSString *text = textView.text;
//    换行等于send
    if ([text rangeOfString:@"\n"].length != 0) {
        NSLog(@"send msgs %@",text);
        
//        去除换行字符
        text = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        
        [self sengMsgsWithText:text bodyType:@"text"];
//        清空数据
        textView.text = nil;
//        发送完消息 把inputview的高度改回来
        self.inputViewHeightConstraint.constant = 50;
    }else{
        NSLog(@"%@",textView.text);
    }
}
#pragma mark - 发送聊天消息
- (void)sengMsgsWithText:(NSString *)text bodyType:(NSString *)bodyType
{
    XMPPMessage *msg = [XMPPMessage messageWithType:@"chat" to:self.friendJid];
//    text :纯文本
//    image 图片

    [msg addAttributeWithName:@"bodyType" stringValue:bodyType];
//    设置内容
    [msg addBody:text];
    NSLog(@"%@",msg);
    [[cCXMPPTool sharedcCXMPPTool].xmppStream sendElement:msg];
}
# pragma mark - 消息滚动到底部
- (void)scrollToTableBottom
{
    
    
    NSInteger lastRow = _resultContr.fetchedObjects.count - 1;
    if (lastRow < 0 ) {
        return;
    }
    NSIndexPath *lastPath = [NSIndexPath indexPathForRow:lastRow inSection:0];
    [self.tableView scrollToRowAtIndexPath:lastPath atScrollPosition:(UITableViewScrollPositionBottom) animated:YES];
}
#pragma mark - 选择图片
- (void)addBtnClick
{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePicker.delegate = self;
    [self presentViewController:imagePicker animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSLog(@"%@",info);
//获取图片
    UIImage *image = info[UIImagePickerControllerOriginalImage];
//把图片发送到文件服务器
//    http post put
    /*
     *put实现文件上传没post繁琐，比post快
     *put的文件上传路径 就是下载路径
     *文件上传路径 http://localhost:8080/imfilesever/Upload/Image/ + "图片名（程序员自己定义）"
     */
//    1.取文件名 用户名 + 时间 年月日分秒
    NSString *user = [cCUserInfo sharedcCUserInfo].user;
    
    NSDateFormatter *dataFormatter = [[NSDateFormatter alloc]init];
    dataFormatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *timeStr = [dataFormatter stringFromDate:[NSDate date]];
    NSString *fileName = [user stringByAppendingString:timeStr];
    
    
//    2.拼接上传路径
    
    NSString *uploadUrl = [@"http://localhost:8080/imfilesever/Upload/Image/"stringByAppendingString:fileName];
    
//   3. 使用HTTP put上传
    [self.httpTool uploadData:UIImageJPEGRepresentation(image, 0.75) url:[NSURL URLWithString:uploadUrl] progressBlock:nil completion:^(NSError *error){
        if (!error) {
            NSLog(@"上传成功");
            [self sengMsgsWithText:uploadUrl bodyType:@"image"];
        }
        else{
            NSLog(@"%@",error);
        }
    }];
    
//图片发送成功，把图片的URL传OpenFire
    
}
@end
